package com.mzxy.mztopline.view;

import android.app.Activity;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Rect;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.Scroller;

import androidx.fragment.app.Fragment;
import androidx.viewpager.widget.ViewPager;

import com.mzxy.mztopline.R;

import java.util.LinkedList;
import java.util.List;

public class SwipeBackLayout extends FrameLayout {
    private  Drawable shadowDrawable;
    private  Scroller scroller;
    private View mcontentView;
    private int mTouchSlop,downX,downY,tempX,tempY;
    private Activity mactivity;
    private List<ViewPager> mViewPagers=new LinkedList<ViewPager>();
    private boolean isSilding;
    private int viewWidth;
    private boolean isFinish;

    public SwipeBackLayout(Context context, AttributeSet attrs) {
    this(context,attrs,0);
    }

    public SwipeBackLayout(Context context, AttributeSet attrs, int defStyle) {
        super(context,attrs,defStyle);
        mTouchSlop= ViewConfiguration.get(context).getScaledTouchSlop();
        scroller=new Scroller(context);
        shadowDrawable=getResources().getDrawable(R.drawable.shadow_left);
    }
    public void attachToActivity(Activity activity){
        mactivity=activity;
        TypedArray array=activity.getTheme().obtainStyledAttributes(
                new int[]{android.R.attr.windowBackground});
                int background=array.getResourceId(0,0);
                array.recycle();
                ViewGroup decor= (ViewGroup) activity.getWindow().getDecorView();
                ViewGroup decorChild= (ViewGroup) decor.getChildAt(0);
                decorChild.setBackgroundResource(background);
                decor.removeView(this);
                addView(decorChild);
                setContentView(decorChild);
                decor.addView(this);
    }

    private void setContentView(View decorChild) {
        mcontentView= (View) decorChild.getParent();
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        ViewPager viewPager = getTouchViewPager(mViewPagers, ev);
        if (viewPager!=null&&viewPager.getCurrentItem()!=0) {
            return super.onInterceptTouchEvent(ev);
        }switch (ev.getAction()){
            case MotionEvent.ACTION_DOWN:
                downX=tempX= (int) ev.getRawX();
                downY=tempY= (int) ev.getRawY();
                break;
            case MotionEvent.ACTION_MOVE:
                int moveX= (int) ev.getRawX();
                if (moveX-downX>mTouchSlop&&Math.abs((int)ev.getRawY()-downY)<mTouchSlop){
                    return true;
                }
        }
        return super.onInterceptTouchEvent(ev);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()){
            case MotionEvent.ACTION_MOVE:
                int moveX= (int) event.getRawX();
                int deltaX=tempX-moveX;
                tempX=moveX;
                if (moveX-downX>mTouchSlop && Math.abs((int)event.getRawY()-downY)<mTouchSlop){
                    isSilding=true;
            }if (moveX-downX>=0&&isSilding){
                    mcontentView.scrollBy(deltaX,0);
            }
                break;
            case MotionEvent.ACTION_UP:
                isSilding=false;
                if (mcontentView.getScrollX()<=-viewWidth/2){
                    isFinish=true;
                    scrollRight();
                }else {
                    scrollOrgin();
                    isFinish=false;
                }
                break;
        }
        return true;
    }

    @Override
    public void computeScroll() {
        if (scroller.computeScrollOffset()){
            mcontentView.scrollTo(scroller.getCurrX(),scroller.getCurrY());
            postInvalidate();
            if (scroller.isFinished()&&isFinish){
                mactivity.finish();
            }
        }
    }

    private void scrollOrgin() {
        int delta=mcontentView.getScrollX();
        scroller.startScroll(mcontentView.getScrollX(),0,-delta,0);
        postInvalidate();
    }

    private void scrollRight() {
        final int delta=(viewWidth+mcontentView.getScrollX());
        scroller.startScroll(mcontentView.getScrollX(),0,-delta+1,0,Math.abs(delta));
        postInvalidate();
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        super.onLayout(changed, left, top, right, bottom);
        if (changed){
            viewWidth=this.getWidth();
            getAllViewPager(mViewPagers,this);
        }
    }

    private void getAllViewPager(List<ViewPager> mViewPagers, ViewGroup parent) {
        int childCount=parent.getChildCount();
        for (int i=0;i<childCount;i++){
            View child=parent.getChildAt(i);
            if (child instanceof ViewGroup){
                mViewPagers.add((ViewPager) child);
            }else if (child instanceof ViewGroup){
                getAllViewPager(mViewPagers, (ViewGroup) child);
            }
        }
    }

    @Override
    protected void dispatchDraw(Canvas canvas) {
        super.dispatchDraw(canvas);
        if (shadowDrawable!=null&&mcontentView!=null){
            int left=mcontentView.getLeft()-shadowDrawable.getIntrinsicWidth();
            int right=left+shadowDrawable.getIntrinsicWidth();
            int top=mcontentView.getTop();
            int bottom=mcontentView.getBottom();
            shadowDrawable.setBounds(left,right,top,bottom);
            shadowDrawable.draw(canvas);
        }
    }

    private ViewPager getTouchViewPager(List<ViewPager>mViewPagers, MotionEvent event) {
        if (mViewPagers==null||mViewPagers.size()==0){
            return  null;
        }
        Rect mRect=new Rect();
        for (ViewPager viewPager:mViewPagers){
            viewPager.getHitRect(mRect);
            if (mRect.contains((int)event.getX(),(int)event.getY())){
                return viewPager;
            }
        }
    return null;
    }
}
